<?php

class CategoryController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/home';
	
	protected function beforeAction($action){
		if(Utils::isAdmin(Yii::app()->user->id)){
			throw  new CHttpException("403","Access Denied");
		}
		return true;
	}

	public function actionAdd($id){
		$category = new Category;
		$category->parent_id=$id;
		$category->title="Title";
		$category->seq = 100;
		$category->save();
		$this->redirect(array("category/admin","id"=>$id));
	}
	public function actionDelete($id){
		$category = Category::model()->findByPk($id);
		$parent_id = $category->parent_id;
		if(Category::model()->count("parent_id=$id")!=0 ||Event::model()->count("category_id=$id")!=0){
			Yii::app()->user->setFlash('failure','You need delete all records under this category.');
		}else{
			$category->delete();
		}
		$this->redirect(array("category/admin","id"=>$parent_id));
	}

	public function actionAdmin($id = 0)
	{
		if(isset($_POST["Category"])){
			foreach($_POST["Category"] as $categoryArr){
				$category = Category::model()->findByPk($categoryArr['id']);
				$category->attributes=$categoryArr;
				$category->description = $categoryArr['description'];
				if(!$category->save()){
					echo $category;exit;
				}
			}
		}
		$criteria = new CDbCriteria;
		$criteria->order = '`seq` asc';
		$criteria->condition = "parent_id=$id";
		$categories = Category::model()->findAll($criteria);
		$curr_category = Category::model()->findByPk($id);
		$this->render('admin',array("categories"=>$categories,"curr_category"=>$curr_category));
	}
}
